package com.gz.mylife.adapter;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gz.mylife.R;
import com.gz.mylife.app.ProductDetail;
import com.gz.mylife.wheel.adapter.AbstractWheelTextAdapter;
import com.gz.mylife.widget.wheel.OnWheelChangedListener2;
import com.gz.mylife.widget.wheel.WheelView2;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.zl.smartmall.library.IShoppingCart;
import com.zl.smartmall.library.listener.DeleteGoodsListener;
import com.zl.smartmall.library.listener.ShoppingCartListener;
import com.zl.smartmall.library.po.ShoppingCartInfo;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.Tools;

public class ShoppingCartAdapter extends BaseAdapter{
	protected static final String TAG = ShoppingCartAdapter.class.getSimpleName();
	private List<ShoppingCartInfo> mDataList;
	private Context mContext;
	private boolean isEditable;
	private UpdataUI mUpdataUI;
	private int windowWidth;
	private View mCurrentView;
	private int selectNum;
	
	private DisplayImageOptions options;
	public ShoppingCartAdapter(Context context,List<ShoppingCartInfo> mDataList,UpdataUI updataUI){
		this.mContext = context;
		this.mDataList = mDataList;
		this.options = buildOptions();
		this.mUpdataUI = updataUI;
		WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
		windowWidth = wm.getDefaultDisplay().getWidth();
	}
	
	private DisplayImageOptions buildOptions() {
		return new DisplayImageOptions.Builder()
        .resetViewBeforeLoading()
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheInMemory()
        .cacheOnDisc()
        .showStubImage(R.drawable.drawable_recent_white)
        .showImageOnFail(R.drawable.drawable_recent_white)
        .imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
        .displayer(new RoundedBitmapDisplayer(5))
        .build();
	}
	

	public void setEditable(boolean isEditable) {
		this.isEditable = isEditable;
		notifyDataSetChanged();
	}



	@Override
	public int getCount() {
		return mDataList.size();
	}

	@Override
	public Object getItem(int arg0) {
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup arg2) {
			final ViewHold holder;
			if(convertView == null){
				holder = new ViewHold();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.shoppingcart_item, null);
				holder.hsView = (HorizontalScrollView) convertView.findViewById(R.id.hs_cart);
				holder.rlLeft = (RelativeLayout) convertView.findViewById(R.id.rl_left);
				holder.rlRight = (RelativeLayout) convertView.findViewById(R.id.rl_right);
				
				holder.pic = (ImageView) convertView.findViewById(R.id.iv_product_pic);
				holder.title = (TextView) convertView.findViewById(R.id.tv_product_title);
				holder.name = (TextView) convertView.findViewById(R.id.tv_product_name);
				holder.price = (TextView) convertView.findViewById(R.id.tv_product_price);
				holder.selectBtn = (ImageView) convertView.findViewById(R.id.btn_product_selected);
				holder.minus = (Button) convertView.findViewById(R.id.btn_minus);
				holder.num = (TextView) convertView.findViewById(R.id.tv_buy_num);
				holder.add = (Button) convertView.findViewById(R.id.btn_add);
				holder.tvBuyNum = (TextView) convertView.findViewById(R.id.tv_buy_num2);
				holder.tvTitleCount = (TextView) convertView.findViewById(R.id.tv_title_count);
				holder.bgAddandminus = (RelativeLayout) convertView.findViewById(R.id.rl_bottom2);
				holder.shoppingName = (TextView) convertView.findViewById(R.id.tv_shopname);
				convertView.setTag(holder);
			}else{
				holder = (ViewHold) convertView.getTag();
			}
			CrashHandler.d("listview", "getview "+position);
			
			LinearLayout.LayoutParams rlLeftparams = (LayoutParams) holder.rlLeft.getLayoutParams();
			rlLeftparams.width = windowWidth;
			
			final ShoppingCartInfo info = mDataList.get(position);
			
			holder.title.setText(info.getProductTitle());
			holder.name.setText(info.getShopName());
			holder.price.setText(info.getSalePrice()+"");
			holder.num.setText(info.getBuyNum()+info.getAddNum()+"");
			holder.tvBuyNum.setText(info.getBuyNum()+info.getAddNum()+"");
			holder.shoppingName.setText(info.getShopName());
//			if(!isEditable){
//				holder.tvBuyNum.setVisibility(View.VISIBLE);
//				holder.tvTitleCount.setVisibility(View.GONE);
//				holder.bgAddandminus.setVisibility(View.GONE);
//			}else{
//				holder.tvBuyNum.setVisibility(View.GONE);
//				holder.tvTitleCount.setVisibility(View.VISIBLE);
//				holder.bgAddandminus.setVisibility(View.VISIBLE);
//			}
			
			
			
			ImageLoader.getInstance().displayImage(info.getPic(), holder.pic, options);
			
			
			holder.title.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(!isEditable){
						Intent intent = new Intent(mContext, ProductDetail.class);
						intent.putExtra("productId", info.getProductId());
						intent.putExtra("shopId", info.getShopId());
						intent.putExtra("mBrandId", 0);
						mContext.startActivity(intent);
					}
				}
			});
			
			if(holder.hsView.getScrollX() != 0){
				holder.hsView.scrollTo(0, 0);
			}
			holder.hsView.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						CrashHandler.d(TAG, "holder.hsView ACTION_DOWN");
						break;
					case MotionEvent.ACTION_MOVE:
						CrashHandler.d(TAG, "holder.hsView ACTION_MOVE");
						break;
					case MotionEvent.ACTION_UP:
						ViewHold holder2 = (ViewHold) v.getTag();
						int scrollx = holder2.hsView.getScrollX();
						int width = holder2.rlRight.getWidth();
						CrashHandler.d(TAG, "scrollx:"+scrollx);
						CrashHandler.d(TAG, "width:"+width);
						if(scrollx<width/2){
							holder2.hsView.scrollTo(0, 0);
						}else{
							holder2.hsView.scrollTo(width, 0);
							mCurrentView = v;
						}
						CrashHandler.d(TAG, "holder.hsView ACTION_UP");
						break;

					default:
						break;
					}
					return false;
				}
			});
			holder.rlLeft.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
							if(holder2.hsView.getScrollX()>0&&holder2.rlLeft != v){
								holder2.hsView.scrollTo(0, 0);
								CrashHandler.d(TAG, "mCurrentView != v");
							}else{
								CrashHandler.d(TAG, "mCurrentView == v");
							}
							if(holder2.rlLeft == v && holder2.hsView.getScrollX() > 0){
								return true;
							}
						}
						CrashHandler.d(TAG, "holder.rlLeft ACTION_DOWN");
						break;
					case MotionEvent.ACTION_MOVE:
						CrashHandler.d(TAG, "holder.rlLeft ACTION_MOVE");
						break;
					case MotionEvent.ACTION_UP:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
						}
						CrashHandler.d(TAG, "holder.rlLeft ACTION_UP");
						break;
						
					default:
						break;
					}
					return false;
				}
			});
			
			holder.rlRight.setTag(info);
			holder.rlRight.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ShoppingCartInfo info = (ShoppingCartInfo) v.getTag();
					mDataList.remove(info);
					notifyDataSetChanged();
					mUpdataUI.update();
					String mDeleteStr = "";
					JSONArray orderArray = new JSONArray();
					JSONObject order = new JSONObject();
					try {
						order.put("act_id", info.getActId());
						order.put("shop_id", info.getShopId());
						order.put("product_id", info.getProductId());
						order.put("num", info.getBuyNum());
					} catch (JSONException e) {
						e.printStackTrace();
					}
					orderArray.put(order);
					if(orderArray.length()>0){
						mDeleteStr = Tools.Base64Encode(orderArray.toString());//Base64.encodeToString(orderArray.toString().getBytes(), Base64.DEFAULT);
						IShoppingCart.getInstance().deleteGoods(mDeleteStr, new DeleteGoodsListener() {
							
							@Override
							public void onResponseFailed() {
								
							}
							
							@Override
							public void onOffline() {
								
							}
							
							@Override
							public void onNoNetWork() {
								
							}
							
							@Override
							public void onNoMoreData() {
								
							}
							
							@Override
							public void onResponseSuccess(List<ShoppingCartInfo> shoppingCartInfos) {
								
							}
						});
					}
				}
			});
			
			holder.pic.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
							if(holder2.hsView.getScrollX()>0&&holder2.pic != v){
								holder2.hsView.scrollTo(0, 0);
								CrashHandler.d(TAG, "holder.pic mCurrentView != v");
							}else{
								CrashHandler.d(TAG, "holder.pic mCurrentView == v");
							}
							if(holder2.pic == v && holder2.hsView.getScrollX() > 0){
								return true;
							}
						}
						CrashHandler.d(TAG, "holder.pic ACTION_DOWN");
						break;
					case MotionEvent.ACTION_MOVE:
						CrashHandler.d(TAG, "holder.pic ACTION_MOVE");
						break;
					case MotionEvent.ACTION_UP:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
						}
						CrashHandler.d(TAG, "holder.pic ACTION_UP");
						break;
						
					default:
						break;
					}
					return false;
				}
			});
			
			holder.title.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
							if(holder2.hsView.getScrollX()>0&&holder2.title != v){
								holder2.hsView.scrollTo(0, 0);
								CrashHandler.d(TAG, "holder.title mCurrentView != v");
							}else{
								CrashHandler.d(TAG, "holder.title mCurrentView == v");
							}
							if(holder2.title == v && holder2.hsView.getScrollX() > 0){
								return true;
							}
						}
						CrashHandler.d(TAG, "holder.title ACTION_DOWN");
						break;
					case MotionEvent.ACTION_MOVE:
						CrashHandler.d(TAG, "holder.title ACTION_MOVE");
						break;
					case MotionEvent.ACTION_UP:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
						}
						CrashHandler.d(TAG, "holder.title ACTION_UP");
						break;
						
					default:
						break;
					}
					return false;
				}
			});
			
			holder.title.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(!isEditable){
						Intent intent = new Intent(mContext, ProductDetail.class);
						intent.putExtra("productId", info.getProductId());
						intent.putExtra("shopId", info.getShopId());
						intent.putExtra("mBrandId", 0);
						mContext.startActivity(intent);
					}
				}
			});
			holder.pic.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(!isEditable){
						Intent intent = new Intent(mContext, ProductDetail.class);
						intent.putExtra("productId", info.getProductId());
						intent.putExtra("shopId", info.getShopId());
						intent.putExtra("mBrandId", 0);
						mContext.startActivity(intent);
					}
				}
			});
			
			holder.selectBtn.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
							if(holder2.hsView.getScrollX()>0&&holder2.selectBtn != v){
								holder2.hsView.scrollTo(0, 0);
								CrashHandler.d(TAG, "holder.pic mCurrentView != v");
							}else{
								CrashHandler.d(TAG, "holder.pic mCurrentView == v");
							}
							if(holder2.selectBtn == v && holder2.hsView.getScrollX() > 0){
								return true;
							}
						}
						CrashHandler.d(TAG, "holder.pic ACTION_DOWN");
						break;
					case MotionEvent.ACTION_MOVE:
						CrashHandler.d(TAG, "holder.pic ACTION_MOVE");
						break;
					case MotionEvent.ACTION_UP:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
						}
						CrashHandler.d(TAG, "holder.pic ACTION_UP");
						break;
						
					default:
						break;
					}
					return false;
				}
			});
			
			if(info.isSeleted()){
				holder.selectBtn.setBackgroundResource(R.drawable.ic_shopping_selected);
			}else{
				holder.selectBtn.setBackgroundResource(R.drawable.ic_shopping_unselected);
			}
			
			holder.selectBtn.setTag(info);
			holder.selectBtn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ShoppingCartInfo info2 = (ShoppingCartInfo) v.getTag();
					if(info2.isSeleted()){
						info2.setSeleted(false);
						if(info2.getProductId() == info.getProductId()){
							v.setBackgroundResource(R.drawable.ic_shopping_unselected);
						}
					}else{
						info2.setSeleted(true);
						if(info2.getProductId() == info.getProductId()){
							v.setBackgroundResource(R.drawable.ic_shopping_selected);
						}
					}
//					countIsAllSeleted();
					mUpdataUI.update();
				}
			});
			
			holder.tvBuyNum.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
							if(holder2.hsView.getScrollX()>0&&holder2.tvBuyNum != v){
								holder2.hsView.scrollTo(0, 0);
								CrashHandler.d(TAG, "holder.tvBuyNum mCurrentView != v");
							}else{
								CrashHandler.d(TAG, "holder.tvBuyNum mCurrentView == v");
							}
							if(holder2.tvBuyNum == v && holder2.hsView.getScrollX() > 0){
								return true;
							}
						}
						CrashHandler.d(TAG, "holder.tvBuyNum ACTION_DOWN");
						break;
					case MotionEvent.ACTION_MOVE:
						CrashHandler.d(TAG, "holder.tvBuyNum ACTION_MOVE");
						break;
					case MotionEvent.ACTION_UP:
						if(mCurrentView != null){
							ViewHold holder2 = (ViewHold) mCurrentView.getTag();
						}
						CrashHandler.d(TAG, "holder.tvBuyNum ACTION_UP");
						break;
						
					default:
						break;
					}
					return false;
				}
			});
			holder.tvBuyNum.setTag(info);
			holder.tvBuyNum.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ShoppingCartInfo info = (ShoppingCartInfo) v.getTag();
					showSelectPop((TextView)v,info);
				}
			});
			
			
		return convertView;
	}
	
	class ViewHold{
		ImageView pic;
		TextView title;
		TextView name;
		TextView price;
		ImageView selectBtn;
		Button minus;//2
		TextView num;//2
		Button add;//2
		TextView tvBuyNum; //1
		TextView tvTitleCount;//2
		RelativeLayout bgAddandminus;
		HorizontalScrollView hsView;
		RelativeLayout rlLeft;
		RelativeLayout rlRight;
		TextView shoppingName;
	}
	
	public static interface UpdataUI{ 
		public void update();
	}
	
	private void showSelectPop(final TextView tvNum,final ShoppingCartInfo info) {
		selectNum = info.getBuyNum();
 		final Dialog dialog = new Dialog(mContext, R.style.DialogTheme);
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.shoppingcart_changenum_dialog, null);
        final WheelView2 wheel = (WheelView2) contentView.findViewById(R.id.wheel1);
        contentView.findViewById(R.id.btn_concel).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
        contentView.findViewById(R.id.btn_ok).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(selectNum != info.getBuyNum()){
					//更改购买数量，同时向服务器发送修改请求
					int addnum = selectNum-info.getBuyNum();
					info.setBuyNum(selectNum);
					tvNum.setText(info.getBuyNum()+"");
					mUpdataUI.update();
					String mDeleteStr = "";
					JSONArray orderArray = new JSONArray();
					JSONObject order = new JSONObject();
					try {
						order.put("act_id", info.getActId());
						order.put("shop_id", info.getShopId());
						order.put("product_id", info.getProductId());
						order.put("num",addnum);
					} catch (JSONException e) {
						e.printStackTrace();
					}
					orderArray.put(order);
					
					if(orderArray.length()>0){
						mDeleteStr = Tools.Base64Encode(orderArray.toString());//Base64.encodeToString(orderArray.toString().getBytes(), Base64.DEFAULT);
						IShoppingCart.getInstance().upDataGoods(mDeleteStr, new ShoppingCartListener() {
							
							@Override
							public void onResponseFailed() {
								
							}
							
							@Override
							public void onOffline() {
								
							}
							
							@Override
							public void onNoNetWork() {
								
							}
							
							@Override
							public void onNoMoreData() {
								
							}
							
							@Override
							public void onResponseSuccess(List<ShoppingCartInfo> shoppingCartListeners) {
								
							}
						});
					}
				}
				dialog.dismiss();
			}
		});
        wheel.addChangingListener(new OnWheelChangedListener2() {
			
			@Override
			public void onChanged(WheelView2 wheel, int oldValue, int newValue) {
				selectNum = newValue%100+1;
			}
		});
        wheel.setViewAdapter(new NumAdapter(mContext));
        dialog.setContentView(contentView);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        wheel.setVisibleItems(5);
        wheel.setCurrentItem(info.getBuyNum()-1+5000);
	}
	
	private class NumAdapter extends AbstractWheelTextAdapter {
        /**
         * Constructor
         */
        protected NumAdapter(Context context) {
            super(context, R.layout.shoppingcart_num_layout, NO_RESOURCE);
            
            setItemTextResource(R.id.country_name);
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent); 
            return view;
        }
        
        @Override
        public int getItemsCount() {
            return 10000;
        }
        
        @Override
        protected CharSequence getItemText(int index) {//设置textview上显示的文本，
            return (index%100+1)+"";
        }
    }
}
